package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Page;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.TbSpecification;
import com.dongdongshop.pojo.TbSpecificationOption;
import com.dongdongshop.service.SpecService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("spec")
public class SpecController {

    @DubboReference
    private SpecService specService;

    @RequestMapping("toShow")
    public String toShow(){
        return "admin/specification";
    }

    @RequestMapping("list")
    @ResponseBody
    public Result list(@RequestParam(defaultValue = "1")Integer pageNum,
                       @RequestParam(defaultValue = "3")Integer pageSize,
                       TbSpecification tbSpecification){
        Page<TbSpecification> page = specService.list(pageNum,pageSize,tbSpecification);
        return Result.response(ResultEnum.SUCCESS).setData(page);
    }

    @RequestMapping("add")
    @ResponseBody
    public Result add(String listJson, TbSpecification tbSpecification){
        //JSONObject.parseArray()：将字符串转化为集合
        List<TbSpecificationOption> options = JSONObject.parseArray(listJson,TbSpecificationOption.class);
        specService.add(tbSpecification,options);
        return Result.response(ResultEnum.SUCCESS);
    }

    @RequestMapping("deleteInfo")
    @ResponseBody
    public Result deleteInfo(Integer[] ids){
        specService.deleteInfo(ids);
        return Result.ok();
    }

    @RequestMapping("toUpdate")
    @ResponseBody
    public Result toUpdate(Long id,Map map){
        TbSpecification tbSpecification = specService.toUpdate(id);
        List<TbSpecificationOption> list = specService.toUpdateOption(id);
        map.put("sp",tbSpecification);
        map.put("ops",list);
        return Result.response(ResultEnum.SUCCESS).setData(map);
    }

    @RequestMapping("updateInfo")
    @ResponseBody
    public Result updateInfo(String listJson, TbSpecification tbSpecification){
        //JSONObject.parseArray()：将字符串转化为集合
        List<TbSpecificationOption> options = JSONObject.parseArray(listJson,TbSpecificationOption.class);
        specService.updateInfo(tbSpecification,options);
        return Result.response(ResultEnum.SUCCESS);
    }


}
